package com.orangelife.mobile.confirmOrder.biz;

import com.curry.android.util.DecimalUtil;
import com.orangelife.mobile.confirmOrder.activity.ShoppingConfirmOrderActivity;
import com.orangelife.mobile.confirmOrder.entity.MerchantInfo;
import com.orangelife.mobile.voucher.biz.SelectedVoucherIDListHelper;
import com.orangelife.mobile.voucher.biz.VoucherBiz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MerchantGoodListHelper，商户商品列表的维护类，做其各种逻辑处理（当然，完全没必要使用一个专门的类来维护List的逻辑处理，用工具类就可以了）
 * Created by asus on 2015/11/1.
 */
public class MerchantOrderListHelper {
    public static final String OTHER_VOUCHER_LIST = "otherIDs";
    public static final String GOOD_ID = "goodID";
    public static final String MER_ID = "merID";
    public static final String TOTAL_COST = "totalCost";
    public static final String TYPE = "type";
    private List<MerchantInfo> mMerchantInfoList = new ArrayList<>();
    public String totalPostogeFee = "0";
    public String totalDisptachFee = "0";
    public String totalVoucherPrice = "0";
    public String totalPrice = "0";
    public String totalGoodsPrice = "0";//商品总金额
    public String deductionPrice = "0";//积分可抵用金额

    public MerchantOrderListHelper(List<Map<String, Object>> selectedMerchantGoodList, List<HashMap<String, Object>> localMerchantGoodList) {
        initMerchantInfoList(selectedMerchantGoodList, localMerchantGoodList);
    }

    public List<MerchantInfo> getMerchantInfoList() {
        return mMerchantInfoList;
    }

    /**
     * 初始化（ 商户商品列表 --> 请求抵用券列表 --> ）带抵用券的商品商户列表 ；
     */
    private void initMerchantInfoList(List<Map<String, Object>> selectedMerchantGoodList, List<HashMap<String, Object>> localMerchantGoodList) {
        for (int i = 0; i < selectedMerchantGoodList.size(); i++) {
            MerchantInfo merchantInfo = new MerchantInfo();
            Map<String, Object> merchantMap = selectedMerchantGoodList.get(i);
            String merchantName = String.valueOf(merchantMap.get("merchantName"));
            String merID = String.valueOf(merchantMap.get("merID"));
            List<Map<String, Object>> goodList = (List<Map<String, Object>>) merchantMap.get("goods");
            List<Map<String, Object>> dispatchList = (List<Map<String, Object>>) merchantMap.get("dispatch");
            merchantInfo.setMerchantName(merchantName);
            merchantInfo.setGoodsList(goodList);
            merchantInfo.setDispatchList(dispatchList);
            merchantInfo.setMerID(merID);
            mMerchantInfoList.add(merchantInfo);
            /*设置商品数量、总价、配送方式*/
            setEveryGoodNumber(merchantInfo, i, localMerchantGoodList);
            setTotalNumAndPrice(merchantInfo);
            setFirstDispatch(i);
             /*请求商品列表之后，此时还未请求到抵用券信息*/
            /*初始化该商户的抵用券信息，默认为暂无抵用券*/
            merchantInfo.setVoucherInfo(VoucherBiz.STR_NO_VOUCHER);
            merchantInfo.setCouponID("");
            merchantInfo.setVoucherValue("0");
        }
    }

    //TODO 四层FOR循环，是否可以优化？

    /**
     * 在将selectedGoodList转为MerchantInfoList的时候，服务端并没有商品数量，必须得从本地获取，并加入其中
     * 给每一个商品设置其选中的数量
     */
    @SuppressWarnings("unchecked")
    private void setEveryGoodNumber(MerchantInfo merchantInfo, int i, List<HashMap<String, Object>> localMerchantGoodList) {
        /*本地的商品的产品规格ID列表*/
        ArrayList<String> localProductIDsList = ((ArrayList<String>) localMerchantGoodList.get(i).get(ShoppingConfirmOrderActivity.PRODUCT_IDS));
        List<Map<String, Object>> serverGoodList = merchantInfo.getGoodsList();
        String serverMerID = merchantInfo.getMerID();
        for (int j = 0; j < localMerchantGoodList.size(); j++) {/*先遍历本地商户数据列表*/
            String localMerID = String.valueOf(localMerchantGoodList.get(j).get(ShoppingConfirmOrderActivity.MER_ID));
            ArrayList<String> localProductIDList = ((ArrayList<String>) localMerchantGoodList.get(j).get(ShoppingConfirmOrderActivity.PRODUCT_IDS));
            ArrayList<String> localProductNumberList = ((ArrayList<String>) localMerchantGoodList.get(j).get(ShoppingConfirmOrderActivity.PRODUCT_NUMBER));
            /*忘了*/
            ArrayList<String> sellPloyIDList = ((ArrayList<String>) localMerchantGoodList.get(j).get(ShoppingConfirmOrderActivity.SELLPLOY_ID));
            if (serverMerID.equals(localMerID)) {/*如果是对应的商户*/
                for (int m = 0; m < serverGoodList.size(); m++) {/*则遍历该服务端商户的商品列表*/
                    String serverProductID = String.valueOf(serverGoodList.get(m).get("productID"));
                    for (int n = 0; n < localProductIDsList.size(); n++) {/*再遍历本地商品ID列表*/
                        String localProductID = localProductIDList.get(n);
                        if (serverProductID.equals(localProductID)) {/*如果是对应的商品*/
                            String goodNum = localProductNumberList.get(n);
                            serverGoodList.get(m).put(ShoppingConfirmOrderActivity.PRODUCT_NUMBER, goodNum);
                            String sellPloyID = sellPloyIDList.get(n);
                            merchantInfo.setSellployId(sellPloyID);
                            break;
                        }
                    }
                }
                break;
            }
        }
    }


    /**
     * 设置首选配送方式
     */
    private void setFirstDispatch(int i) {
        if (!checkList(i)) {
            return;
        }
        MerchantInfo merchantInfo = mMerchantInfoList.get(i);
        for (int j = 0; j < merchantInfo.getDispatchList().size(); j++) {
            Map<String, Object> dispatchMap = merchantInfo.getDispatchList().get(j);
            if (dispatchMap.get("status").equals("1")) {/*什么意思？*/
                merchantInfo.setShipCost(String.valueOf(dispatchMap.get("shipCost")));
                merchantInfo.setDispatchFee(String.valueOf(dispatchMap.get("dispatchFee")));
                merchantInfo.setSelectedDispatchName(String.valueOf(dispatchMap.get("dispatchName")));
                merchantInfo.setDispatchType(String.valueOf(dispatchMap.get("dispatchType")));
                merchantInfo.setDispatchID(String.valueOf(dispatchMap.get("dispatchID")));
                merchantInfo.setLimitFee(String.valueOf(dispatchMap.get("limitFee")));
                setFreeIfOverLimitFee(i);
                break;
            }
        }
    }

    /**
     * 总价达到满免值
     */
    public void setFreeIfOverLimitFee(int i) {
        if (!checkList(i)) {
            return;
        }
        MerchantInfo merchantInfo = mMerchantInfoList.get(i);
        if (Double.parseDouble(merchantInfo.getSingleTotalPrice()) >=
                Double.parseDouble(merchantInfo.getLimitFee())) {
            merchantInfo.setShipCost("0");
            merchantInfo.setDispatchFee("0");
        }
    }

    private boolean checkList(int i) {
        if (mMerchantInfoList == null || i < 0 || i >= mMerchantInfoList.size()) {
            return false;
        }
        return true;
    }

    /**
     * 设置每个商户的商品总价和总量
     */
    private void setTotalNumAndPrice(MerchantInfo merchantInfo) {
        String totalPriceWithOneMerchant = "0";
        String totalNumWithOneMerchant = "0";
        for (int i = 0; i < merchantInfo.getGoodsList().size(); i++) {
            Map<String, Object> goodMap = merchantInfo.getGoodsList().get(i);
            String goodNum = String.valueOf(goodMap.get(ShoppingConfirmOrderActivity.PRODUCT_NUMBER));
            String oneGoodPrice = String.valueOf(goodMap.get("price"));
            // TODO: 2016/2/29 这里会空指针？
            String goodsTotalPrice = DecimalUtil.multiply(goodNum, oneGoodPrice);
            totalPriceWithOneMerchant = DecimalUtil.add(totalPriceWithOneMerchant, goodsTotalPrice);
            totalNumWithOneMerchant = DecimalUtil.add(totalNumWithOneMerchant, goodMap.get(ShoppingConfirmOrderActivity.PRODUCT_NUMBER).toString());
            merchantInfo.setGoodsID(String.valueOf(goodMap.get("goodsID")));
        }
        merchantInfo.setSingleTotalPrice(totalPriceWithOneMerchant);/*商品总价*/
        merchantInfo.setSingleGoodsNumber(totalNumWithOneMerchant);/*商品总量*/
    }

    /**
     * 获取商户的可用的最高金额抵用券列表之后，做两件事，1、设置抵用券列表的默认选中的抵用券ID，2、初始化商户的抵用券信息
     *
     * @param highestPriceVoucherList 商户的可用的最高金额抵用券列表
     */
    public void addVoucherHighestPrice(List<Map<String, Object>> highestPriceVoucherList) {
        for (int i = 0; i < mMerchantInfoList.size(); i++) {
            MerchantInfo mi = mMerchantInfoList.get(i);
            String merID = mi.getMerID();
            for (int j = 0; j < highestPriceVoucherList.size(); j++) {
                String newMerID = String.valueOf(highestPriceVoucherList.get(j).get("merID"));
                if (newMerID.equals(merID)) {
                    String voucherID = String.valueOf(highestPriceVoucherList.get(j).get("couponID"));
                    /*默认的商户的抵用券*/
                    SelectedVoucherIDListHelper.getInstance().addSelectedVoucherID(voucherID, newMerID);
                    /*设置该商家可用的最高金额抵用券*/
                    String highestPrice = String.valueOf(highestPriceVoucherList.get(j).get("money"));
                    mi.setVoucherInfo(highestPriceVoucherList.get(j).get("money") + "元抵用券");
                    mi.setVoucherValue(highestPrice);
                    mi.setVoucherColor(0);
                }
            }
        }
    }

    /**
     */
    public void updateMerchantVoucherInfo() {
        String fromMerID = SelectedVoucherIDListHelper.getInstance().getVoucherListMapKey();
        for (int i = 0; i < mMerchantInfoList.size(); i++) {
            MerchantInfo mi = mMerchantInfoList.get(i);
            String merID = mi.getMerID();
            if (merID.equals(fromMerID)) {/*如果是选用抵用券的商户，则处理*/
                String oldVoucherInfo = mi.getVoucherInfo();
                String newVoucherInfo = VoucherBiz.getVoucherInfo(oldVoucherInfo);
                mi.setVoucherInfo(newVoucherInfo);
                mi.setVoucherValue(SelectedVoucherIDListHelper.getInstance().getTotalSelectedVoucherPrice());/*抵用券总价*/
                break;
            }
        }
    }
}
